﻿//-----------------------------------------------------------------------------
// File: crc.h
// Desc: crc算法
// author: ut
// Date: 2003/11/13
//-----------------------------------------------------------------------------
#pragma once
#include "public_table.h"

//-----------------------------------------------------------------------------
// CRC32算法
//-----------------------------------------------------------------------------
unsigned long Crc32(const char * lpData, unsigned long dwCrc=0);
unsigned long Crc32Low(const char * lpData, unsigned long dwCrc=0);
unsigned long Crc32(unsigned char * pData, int nCount, unsigned long dwCrc=0);



//-----------------------------------------------------------------------------
// 计算ASCII字符串的32位CRC
//-----------------------------------------------------------------------------
unsigned long Crc32(const char * lpData, unsigned long dwCrc)
{
    unsigned int _crc = (unsigned int)dwCrc;
	unsigned char * p = (unsigned char *)lpData;
	_crc ^= unsigned int(-1);

	while(*p)
	{
		_crc = (_crc >> 8) ^ (unsigned int)g_CrcTable[(_crc & 0xFF) ^ *p++];
	}
    
    _crc ^= unsigned int(-1);

    return _crc;
}

//-----------------------------------------------------------------------------
// 计算ASCII字符串的小写32位CRC
//-----------------------------------------------------------------------------
unsigned long Crc32Low(const char * lpData, unsigned long dwCrc)
{
    unsigned int _crc = (unsigned int)dwCrc;
	unsigned char * p = (unsigned char *)lpData;
	_crc ^= unsigned int(-1);

	while(*p)
	{
		_crc = (_crc >> 8) ^ (unsigned int)g_CrcTable[(_crc & 0xFF) ^ (((*p>=0x41 && *p<=0x5A)?(*p+0x20):*p))];
		++p;
	}
    
    _crc ^= unsigned int(-1);

	return _crc;
}


//-----------------------------------------------------------------------------
// 计算32位CRC,字节数组
//-----------------------------------------------------------------------------
unsigned long Crc32(unsigned char * pData, int nCount, unsigned long dwCrc)
{
	unsigned int _crc = (unsigned int)dwCrc;
    _crc ^= unsigned int(-1);

	while(nCount--) 
		_crc = (_crc >> 8) ^ (unsigned int)g_CrcTable[(_crc & 0xFF) ^ *pData++];

    _crc ^= unsigned int(-1);
    
	return _crc;
}

